﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace TICC2480MTClient
{
    public partial class TIConnectionSettingsUC : UserControl
    {
        private TIRoverController tiRoverController;
        public TIRoverController TIRoverController
        {
            get { return tiRoverController; }
            set { tiRoverController = value; }
        }

        public TIConnectionSettingsUC()
        {
            InitializeComponent();
        }

        private void cbPortNames_DropDown(object sender, EventArgs e)
        {
            string selected = cbPortNames.SelectedItem as string;
            cbPortNames.DataSource = SerialPort.GetPortNames();
            cbPortNames.SelectedItem = selected;

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            tiRoverController.SelectedPort = cbPortNames.SelectedItem as string;
            tiRoverController.Start();
            //tiRoverController.Bind();
            tiRoverController.CommandReceived += new EventHandler<PacketEventArgs>(tiRoverController_CommandReceived);
        }


        private void btnBind_Click(object sender, EventArgs e)
        {
            tiRoverController.Bind();
        }


        void tiRoverController_CommandReceived(object sender, PacketEventArgs e)
        {
            ShowReceivedCommand(e.Packet);
        }

        private delegate void ShowReceivedCommandDelegate(SerialPacket serialPacket);
        private void ShowReceivedCommand(SerialPacket serialPacket)
        {
            if (lvMessages.InvokeRequired)
                lvMessages.Invoke(new ShowReceivedCommandDelegate(ShowReceivedCommand),
                    serialPacket);
            else
            {
                lvMessages.Items.Add(new ListViewItem(new string[] { 
                    serialPacket.CMD0.ToString("X2"),
                    serialPacket.CMD1.ToString("X2"),
                    serialPacket.DataAsHex,
                    serialPacket.Command,

                }));
            }

        }

    }
}
